package com.efounder.model;

import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StatFs;
import android.widget.Toast;

import com.efounder.chat.model.Constant;
import com.efounder.chat.utils.CommonThreadPoolUtils;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.util.AppContext;
import com.efounder.util.PackgeFileCheckUtil;
import com.pansoft.resmanager.VersionManager;
import com.pansoft.resmanager.ZipUtil;
import com.utilcode.util.FileUtils;
import com.zhuiji7.filedownloader.download.DownLoadListener;
import com.zhuiji7.filedownloader.download.DownLoadManager;
import com.zhuiji7.filedownloader.download.DownLoadService;
import com.zhuiji7.filedownloader.download.dbcontrol.FileHelper;
import com.zhuiji7.filedownloader.download.dbcontrol.bean.SQLDownLoadInfo;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;

import java.io.File;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import static com.efounder.frame.utils.Constants.KEY_SETTING_APPID;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_ADDRESS;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_PATH;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_PORT;
import static com.efounder.util.AppContext.getInstance;

/**
 * Created by lch on 2016/8/25 0025.
 */

public class RESUpdateManager {

    private String resUrl;
    private String TAG = "CheckRESVersionUtil";
    private CheckRESUtilInterface checkRESVersionUtilInterface;
    /*使用DownLoadManager时只能通过DownLoadService.getDownLoadManager()的方式来获取下载管理器，不能通过new DownLoadManager()的方式创建下载管理器*/
    private DownLoadManager manager;
    private String versionFromServer;


    private static String filename = Constant.ResFileName;

    private static float lastScale, nowScale;
    private static boolean isPaused = false;

    //TaskInfo info = new TaskInfo();

    public RESUpdateManager() {
        resUrl = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE) + "://" + EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_ADDRESS) + ":"
                + EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PORT) + "/"
                + EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PATH) + "/MobileResource/" + EnvironmentVariable.getProperty(KEY_SETTING_APPID)
                + "/updateAndroidForWeChat.zip";
    }

    public void start(String url, CheckRESUtilInterface _checkRESVersionUtilInterface) {
        resUrl = url;
        checkRESVersionUtilInterface = _checkRESVersionUtilInterface;
        startDownLoad();
    }


    public boolean checkIsNeedToDown(String _versionFromServer) {
        versionFromServer = _versionFromServer;
        boolean fileIsFull = PackgeFileCheckUtil.checkFileIsFull(AppContext.getInstance());
        if (!fileIsFull) {
            //配置文件不齐全
            return true;
        }
        // 判断package目录是否存在
        String path = Constant.appSdcardLocation;
        File packageFileDir = new File(path);

        //
        File versionFile = new File(Constant.UNZIP_DIR + "/" + versionFromServer);
        if (versionFile.exists()) {
            return false;
        }
        // 如果版本号不同或者为空，则下载资源文件
        if (VersionManager.isFirstToRequest(AppContext.getInstance())) {
            //清除上一个版本的res
            String filelocation = FileHelper.getBaseFilePath() + VersionManager.getVersion(AppContext.getInstance());
            File downloadFile = new File(filelocation);
            if (downloadFile.exists()) {
                downloadFile.delete();
            }
            return true;
            // 判断是不是最新版本的同时也要判断sd卡中espmobile文件夹是否存在，如果不存在同样需要下载资源文件
        } else if (getSDFreeSize() < 150) {
            Toast.makeText(getInstance(), "空间不足。", Toast.LENGTH_SHORT).show();
            return false;
        } else if (!VersionManager.isLastVersion(AppContext.getInstance(),
                versionFromServer) || !packageFileDir.exists()) {
            //清除上一个版本的res
            String fileLocation = FileHelper.getBaseFilePath() + "/" + VersionManager.getVersion(AppContext.getInstance());
            FileHelper.DeleteFolder(fileLocation);
            String fileLocation1 = Constant.UNZIP_DIR + "/" + VersionManager.getVersion(AppContext.getInstance());
            FileHelper.DeleteFolder(fileLocation1);
            return true;
        } else {

            return false;

        }
    }

    private void startDownLoad() {
        /*获取下载管理器*/
        manager = DownLoadService.getDownLoadManager();

        if (manager == null) {
            return;
        }

        /*设置用户ID，客户端切换用户时可以显示相应用户的下载任务*/
        manager.changeUser(versionFromServer);

        /*断点续传需要服务器的支持，设置该项时要先确保服务器支持断点续传功能*/
        manager.setSupportBreakpoint(true);

        manager.setCurrentTask(filename);

        /*服务器一般会有个区分不同文件的唯一ID，用以处理文件重名的情况*/
        // info.setFileName(filename);
        // info.setTaskID(filename);

        /*将任务添加到下载队列，下载器会自动开始下载*/
        int i = manager.addTask(Constant.ResFileName, resUrl, Constant.ResFileName);

//        final Timer timerFresh = new Timer();
//        timerFresh.schedule(new TimerTask() {
//            public void run() {
//                if (lastScale == nowScale && !isPaused && nowScale != 0) {
//
//                    downErrorHandler.sendEmptyMessage(0);
//                }
//                nowScale = lastScale;
//                if ((int) (lastScale * 100) == 100)
//                    timerFresh.cancel();
//            }
//        }, 1000, 10000);
        final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
                new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(false).build());
        executorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (lastScale == nowScale && !isPaused && nowScale != 0) {
                    downErrorHandler.sendEmptyMessage(0);
                    //  Toast.makeText(context, "网络不稳定，请稍后再试，或者点击进度条双击右边按钮", 200).show();
                }
                nowScale = lastScale;
                if ((int) (lastScale * 100) == 100) {
                    executorService.shutdown();
                }
            }
        }, 1000, 10000, TimeUnit.MILLISECONDS);

        manager.setSingleTaskListener(Constant.ResFileName, new DownLoadListener() {
            @Override
            public void onStart(SQLDownLoadInfo sqlDownLoadInfo) {
            }

            @Override
            public void onProgress(SQLDownLoadInfo sqlDownLoadInfo, boolean isSupportBreakpoint) {
                //info.setDownFileSize(sqlDownLoadInfo.getDownloadSize());
                //info.setFileSize(sqlDownLoadInfo.getFileSize());

                lastScale = (float) sqlDownLoadInfo.getDownloadSize() / sqlDownLoadInfo.getFileSize();
                Message message = new Message();
                message.arg1 = (int) (lastScale * 100);
                downProgressHandler.sendMessage(message);//发送message信息

            }

            @Override
            public void onStop(SQLDownLoadInfo sqlDownLoadInfo, boolean isSupportBreakpoint) {
                checkRESVersionUtilInterface.stop();
            }

            @Override
            public void onError(SQLDownLoadInfo sqlDownLoadInfo) {
                /// manager.deleteTask(filename);
                checkRESVersionUtilInterface.error();
                //如果出现其他类型的异常，会删除这条任务及cache文件，并重新启动任务
                manager.deleteTask(Constant.ResFileName);
                int i = manager.addTask(Constant.ResFileName, resUrl, Constant.ResFileName);
                //info.setOnDownloading(true);
                manager.setSingleTaskListener(Constant.ResFileName, this);
                manager.startTask(manager.getCurrentTask());
            }

            @Override
            public void onSuccess(SQLDownLoadInfo sqlDownLoadInfo) {
                AppContext.getInstance().stopService(new Intent(AppContext.getInstance(), DownLoadService.class));
                final String TEMP_FILEPATH = FileHelper.getFileDefaultPath();
                String filePath = TEMP_FILEPATH + "/(" + FileHelper.filterIDChars(sqlDownLoadInfo.getFileName()) + ")" + sqlDownLoadInfo.getFileName();
                checkRESVersionUtilInterface.downloadOver(filePath);
            }

            @Override
            public void onNetError(SQLDownLoadInfo sqlDownLoadInfo) {
                try {
                    Thread.sleep(3000);
                    manager.startTask(manager.getCurrentTask());
                } catch (Exception e) {
                }
            }
        });
        //如果已经下载完毕
        if (i == -1) {

            String TEMP_FILEPATH = FileHelper.getFileDefaultPath();
            String oldPath = TEMP_FILEPATH + "/(" + FileHelper.filterIDChars(filename) + ")" + filename;

            checkRESVersionUtilInterface.downloadOver(oldPath);
        } else {
            //info.setOnDownloading(true);
            manager.startTask(Constant.ResFileName);
            //checkRESVersionUtilInterface.startDown(((float) info.getDownFileSize() / info.getFileSize()) * 100);
        }

    }


    private static Handler downErrorHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Toast.makeText(AppContext.getInstance(), "网络不稳定。", 200).show();
        }
    };

    public void stopTask() {
        //info.setOnDownloading(false);
        if (manager != null) {
            manager.stopTask(Constant.ResFileName);
        }
        isPaused = true;
        AppContext.getInstance().stopService(new Intent(AppContext.getInstance(), DownLoadService.class));
    }

    public void startTask() {
        //info.setOnDownloading(true);
        manager.startTask(Constant.ResFileName);
        isPaused = false;
    }

    /**
     * 解压文件
     */
    public void unzipAndEncryptFile(final String filePath) {

        CommonThreadPoolUtils.execute(
                new Runnable() {
                    @Override
                    public void run() {
                        String newPath = Constant.RES_DIR + "/" + filename;
                        FileHelper.copyFile(filePath, newPath);
                        //删除原有的解压缩后的文件
                        //deleteUnzipRes();
                        ZipUtil zUtil = new ZipUtil();
                        boolean issuccessZip;

                        //将更新的zip解压到临时目录
                        issuccessZip = zUtil.unZip(newPath, Constant.UNZIP_DIR);
                        if (issuccessZip) {
                            //资源文件解压完毕,生成一个版本号文件放在本地
                            FileUtils.createOrExistsFile(Constant.UNZIP_DIR + "/" + versionFromServer);
                            checkRESVersionUtilInterface.unZIPOVER(versionFromServer);
                        }

                    }
                });
    }

    /**
     * 得到sd卡的剩余空间
     *
     * @return
     */
    public long getSDFreeSize() {
        // 取得SD卡文件路径
        File path = Environment.getExternalStorageDirectory();
        StatFs sf = new StatFs(path.getPath());
        // 获取单个数据块的大小(Byte)
        long blockSize = sf.getBlockSize();
        // 空闲的数据块的数量
        long freeBlocks = sf.getAvailableBlocks();
        // 返回SD卡空闲大小
        // return freeBlocks * blockSize; //单位Byte
        // return (freeBlocks * blockSize)/1024; //单位KB
        return (freeBlocks * blockSize) / 1024 / 1024; // 单位MB
    }

    private Handler downProgressHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            checkRESVersionUtilInterface.updateProgress(msg.arg1);
        }
    };

}



